#!/usr/bin/env python3
"""
验证AKShare配置完整性
"""

import akshare as ak
from config import AKSHARE_CONFIG, PERIOD_MAPPING
from data_fetcher import DataFetcher
import pandas as pd

def verify_akshare_installation():
    """验证AKShare安装"""
    print("🔍 验证AKShare安装...")
    print("-" * 40)
    
    try:
        version = ak.__version__
        print(f"✅ AKShare版本: {version}")
        
        # 测试基本功能
        stock_info = ak.stock_zh_a_spot_em()
        print(f"✅ 基本功能测试通过，获取到{len(stock_info)}只股票信息")
        
        return True
    except Exception as e:
        print(f"❌ AKShare安装验证失败: {e}")
        return False

def verify_config_settings():
    """验证配置设置"""
    print("\n🔧 验证配置设置...")
    print("-" * 40)
    
    try:
        # 检查AKShare配置
        print("📋 AKShare配置:")
        for key, value in AKSHARE_CONFIG.items():
            print(f"   {key}: {value}")
        
        # 检查周期映射
        print("\n📅 周期映射配置:")
        akshare_mapping = PERIOD_MAPPING.get('akshare', {})
        for period, mapping in akshare_mapping.items():
            print(f"   {period}: {mapping}")
        
        print("✅ 配置设置验证通过")
        return True
        
    except Exception as e:
        print(f"❌ 配置设置验证失败: {e}")
        return False

def verify_data_fetcher_integration():
    """验证数据获取器集成"""
    print("\n🔗 验证数据获取器集成...")
    print("-" * 40)
    
    try:
        fetcher = DataFetcher()
        
        # 测试AKShare方法
        test_symbol = "000001"
        print(f"📊 测试股票代码: {test_symbol}")
        
        # 测试代码标准化
        normalized = fetcher._normalize_akshare_symbol(test_symbol)
        print(f"   标准化结果: {normalized}")
        
        # 测试时间范围计算
        start_date, end_date = fetcher._calculate_date_range('日线')
        print(f"   时间范围: {start_date} - {end_date}")
        
        # 测试数据获取
        df = fetcher._fetch_akshare(test_symbol, '日线')
        if not df.empty:
            print(f"✅ 数据获取成功: {len(df)} 条记录")
            print(f"   列数: {len(df.columns)}")
            print(f"   时间范围: {df['timestamp'].min().strftime('%Y-%m-%d')} 至 {df['timestamp'].max().strftime('%Y-%m-%d')}")
        else:
            print("❌ 数据获取失败")
            return False
        
        print("✅ 数据获取器集成验证通过")
        return True
        
    except Exception as e:
        print(f"❌ 数据获取器集成验证失败: {e}")
        return False

def verify_stock_analyzer_compatibility():
    """验证股票分析器兼容性"""
    print("\n📈 验证股票分析器兼容性...")
    print("-" * 40)
    
    try:
        # 模拟股票分析器调用
        fetcher = DataFetcher()
        
        # 测试不同格式的股票代码
        test_codes = ['000001', '000001.SZ', '600000', '600000.SH']
        
        for code in test_codes:
            df = fetcher._fetch_akshare(code, '日线')
            if not df.empty:
                print(f"✅ {code}: 获取{len(df)}条数据")
            else:
                print(f"❌ {code}: 获取失败")
                return False
        
        print("✅ 股票分析器兼容性验证通过")
        return True
        
    except Exception as e:
        print(f"❌ 股票分析器兼容性验证失败: {e}")
        return False

def verify_performance():
    """验证性能表现"""
    print("\n⚡ 验证性能表现...")
    print("-" * 40)
    
    try:
        import time
        
        fetcher = DataFetcher()
        test_symbol = "000001"
        
        # 测试不同周期的获取速度
        periods = ['日线', '周线', '月线']
        
        for period in periods:
            start_time = time.time()
            df = fetcher._fetch_akshare(test_symbol, period)
            end_time = time.time()
            
            if not df.empty:
                duration = end_time - start_time
                print(f"✅ {period}: {len(df)}条数据，耗时{duration:.2f}秒")
            else:
                print(f"❌ {period}: 获取失败")
        
        print("✅ 性能表现验证通过")
        return True
        
    except Exception as e:
        print(f"❌ 性能表现验证失败: {e}")
        return False

def main():
    """主验证流程"""
    print("🚀 AKShare配置完整性验证")
    print("=" * 60)
    
    # 执行所有验证
    tests = [
        ("AKShare安装", verify_akshare_installation),
        ("配置设置", verify_config_settings),
        ("数据获取器集成", verify_data_fetcher_integration),
        ("股票分析器兼容性", verify_stock_analyzer_compatibility),
        ("性能表现", verify_performance)
    ]
    
    passed = 0
    total = len(tests)
    
    for test_name, test_func in tests:
        try:
            if test_func():
                passed += 1
        except Exception as e:
            print(f"❌ {test_name}验证异常: {e}")
    
    # 总结
    print("\n" + "=" * 60)
    print("📊 验证结果总结")
    print("=" * 60)
    print(f"通过测试: {passed}/{total}")
    print(f"成功率: {passed/total*100:.1f}%")
    
    if passed == total:
        print("🎉 AKShare配置完整性验证全部通过！")
        print("✅ 系统已准备就绪，可以使用AKShare作为数据源")
    elif passed > total * 0.8:
        print("⚠️ AKShare配置基本正常，但有部分问题需要关注")
    else:
        print("❌ AKShare配置存在重大问题，需要进一步检查")
    
    # 使用建议
    print(f"\n💡 使用建议:")
    print("1. 推荐使用Baostock作为主要数据源（默认配置）")
    print("2. AKShare作为备用数据源，提供更丰富的数据类型")
    print("3. 可通过环境变量 DATA_SOURCE=akshare 切换到AKShare")
    print("4. 支持多种股票代码格式，自动标准化处理")

if __name__ == "__main__":
    main()
